from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings
from oauth.constants import ACCESS_TOKEN_EXPIRES


def check_access_token(access_code_openid):
    """
    反解\反序列化
    :param access_code_openid: openid
    :return: data
    """
    # 创建序列化　反序列化和　序列化一致
    s = Serializer(settings.SECRET_KEY, ACCESS_TOKEN_EXPIRES)
    # 判断是否存在openid
    try:
        data = s.loads(access_code_openid)
    except BadData:
        return None
    else:
        return data.get("openid")


def generate_access_token(openid):

    # 创建序列化
    # s = Serializer(越复杂越安全, 过期时间)
    s = Serializer(settings.SECRET_KEY, ACCESS_TOKEN_EXPIRES)
    # 构造内容
    data = {"openid": openid}
    # 调用dumps进行序列化
    token = s.dumps(data)  # dumps将字典转化为字符串类型
    # 返回函数
    return token.decode()